<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>员工管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }

        .header-section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }

        .btn-primary:hover {
            background-color: #45a049;
        }

        .btn-warning {
            background-color: #ff9800;
            color: white;
        }

        .btn-warning:hover {
            background-color: #e68a00;
        }

        .btn-danger {
            background-color: #f44336;
            color: white;
        }

        .btn-danger:hover {
            background-color: #d32f2f;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }

        tr:hover {
            background-color: #f9f9f9;
        }

        .action-cell {
            display: flex;
            gap: 5px;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 10% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 50%;
            border-radius: 5px;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: black;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-actions {
            text-align: right;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>员工管理系统</h1>

    <div class="header-section">
        <h2>员工列表</h2>
        <button id="addEmployeeBtn" class="btn btn-primary">新增员工</button>
    </div>

    <table id="employeeTable">
        <thead>
        <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>年龄</th>
            <th>密码</th>
            <th>邮箱</th>
            <th>管理员</th>
            <th>部门ID</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- 员工数据将在这里加载 -->
        </tbody>
    </table>
</div>

<!-- 新增/编辑员工模态框 -->
<div id="employeeModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2 id="modalTitle">新增员工</h2>
        <form id="employeeForm">
            <input type="hidden" id="employeeId">

            <div class="form-group">
                <label for="username">用户名:</label>
                <input type="text" id="username" required>
            </div>

            <div class="form-group">
                <label for="age">年龄:</label>
                <input type="number" id="age" required>
            </div>

            <div class="form-group">
                <label for="password">密码:</label>
                <input type="password" id="password" required>
            </div>

            <div class="form-group">
                <label for="email">邮箱:</label>
                <input type="email" id="email" required>
            </div>

            <div class="form-group">
                <label for="admin">管理员:</label>
                <select id="admin" required>
                    <option value="false">否</option>
                    <option value="true">是</option>
                </select>
            </div>

            <div class="form-group">
                <label for="deptId">部门ID:</label>
                <input type="number" id="deptId" required>
            </div>

            <div class="form-actions">
                <button type="button" id="cancelBtn" class="btn">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<script>
    // DOM元素
    const addEmployeeBtn = document.getElementById('addEmployeeBtn');
    const employeeTable = document.getElementById('employeeTable').getElementsByTagName('tbody')[0];
    const modal = document.getElementById('employeeModal');
    const modalTitle = document.getElementById('modalTitle');
    const employeeForm = document.getElementById('employeeForm');
    const closeBtn = document.querySelector('.close');
    const cancelBtn = document.getElementById('cancelBtn');

    // 表单字段
    const employeeIdField = document.getElementById('employeeId');
    const usernameField = document.getElementById('username');
    const ageField = document.getElementById('age');
    const passwordField = document.getElementById('password');
    const emailField = document.getElementById('email');
    const adminField = document.getElementById('admin');
    const deptIdField = document.getElementById('deptId');

    // 事件监听
    addEmployeeBtn.addEventListener('click', openAddModal);
    closeBtn.addEventListener('click', closeModal);
    cancelBtn.addEventListener('click', closeModal);
    employeeForm.addEventListener('submit', handleFormSubmit);

    // 当前操作（新增或编辑）
    let currentAction = 'add';
    let currentEmployeeId = null;

    // 页面加载时获取员工数据
    document.addEventListener('DOMContentLoaded', loadEmployees);

    // 函数定义
    function loadEmployees() {
        fetch('/employees')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderEmployees(data.data);
                } else {
                    alert('加载员工列表失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('错误:', error);
                alert('加载员工列表时发生错误');
            });
    }

    function renderEmployees(employees) {
        employeeTable.innerHTML = '';

        employees.forEach(employee => {
            const row = document.createElement('tr');

            row.innerHTML = `
                    <td>${employee.id}</td>
                    <td>${employee.username}</td>
                    <td>${employee.age}</td>
                    <td>${employee.password ? '*****' : '未设置'}</td>
                    <td>${employee.email}</td>
                    <td>${employee.admin ? '是' : '否'}</td>
                    <td>${employee.deptId}</td>
                    <td class="action-cell">
                        <button class="btn btn-warning edit-btn" data-id="${employee.id}">编辑</button>
                        <button class="btn btn-danger delete-btn" data-id="${employee.id}">删除</button>
                    </td>
                `;

            employeeTable.appendChild(row);
        });

        // 为编辑和删除按钮添加事件监听
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', openEditModal);
        });

        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', deleteEmployee);
        });
    }

    function openAddModal() {
        currentAction = 'add';
        modalTitle.textContent = '新增员工';
        employeeForm.reset();
        employeeIdField.value = '';
        modal.style.display = 'block';
    }

    function openEditModal(event) {
        currentAction = 'edit';
        currentEmployeeId = event.target.getAttribute('data-id');
        modalTitle.textContent = '编辑员工';

        // 获取员工数据
        fetch(`/employees/${currentEmployeeId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const employee = data.data;
                    // 数据回显到表单
                    employeeIdField.value = employee.id;
                    usernameField.value = employee.username;
                    ageField.value = employee.age;
                    passwordField.value = employee.password; // 出于安全考虑，不显示原密码
                    emailField.value = employee.email;
                    adminField.value = employee.admin ? 'true' : 'false';
                    deptIdField.value = employee.deptId;
                    modal.style.display = 'block';
                } else {
                    alert('获取员工数据失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('错误:', error);
                alert('获取员工数据时发生错误');
            });
    }

    function closeModal() {
        modal.style.display = 'none';
    }

    function handleFormSubmit(event) {
        event.preventDefault();

        const employeeData = {
            username: usernameField.value,
            age: parseInt(ageField.value),
            password: passwordField.value,
            email: emailField.value,
            admin: adminField.value === 'true',
            deptId: parseInt(deptIdField.value)
        };

        if (currentAction === 'edit') {
            employeeData.id = parseInt(employeeIdField.value);
            updateEmployee(employeeData);
        } else {
            addEmployee(employeeData);
        }
    }

    function addEmployee(employeeData) {
        fetch('/employees', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(employeeData)
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadEmployees();
                    closeModal();
                    alert('员工添加成功');
                } else {
                    alert('添加员工失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('错误:', error);
                alert('添加员工时发生错误');
            });
    }

    function updateEmployee(employeeData) {
        fetch('/employees', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(employeeData)
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadEmployees();
                    closeModal();
                    alert('员工信息更新成功');
                } else {
                    alert('更新员工信息失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('错误:', error);
                alert('更新员工信息时发生错误');
            });
    }

    function deleteEmployee(event) {
        const employeeId = event.target.getAttribute('data-id');

        if (confirm('确定要删除此员工吗？')) {
            fetch('/employees?id=' + employeeId, {
                method: 'DELETE'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        loadEmployees();
                        alert('员工删除成功');
                    } else {
                        alert('删除员工失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('错误:', error);
                    alert('删除员工时发生错误');
                });
        }
    }

    // 点击模态框外部关闭模态框
    window.addEventListener('click', (event) => {
        if (event.target === modal) {
            closeModal();
        }
    });
</script>
</body>
</html>